package com.study.reconnect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: NettyClient
 * @Description:
 * @Date 2024/04/30 15:37
 * @Author songshaoqiu
 **/
public class NettyClient {
    private Bootstrap  bootstrap;

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public void setBootstrap(Bootstrap bootstrap) {
        this.bootstrap = bootstrap;
    }

    public static void main(String[] args) {
        NettyClient nettyClient = new NettyClient();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        nettyClient.setBootstrap(bootstrap);
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new ReConnectClientHandler(nettyClient));
                    }
                });
        nettyClient.connect();
    }

    public void connect(){
        ChannelFuture connect = bootstrap.connect("127.0.0.1", 9090);
        connect.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                ChannelId id = channelFuture.channel().id();
                System.out.println("每次【客户端连接的channelId】:"+id);
                if (channelFuture.isSuccess()){
                    System.out.println("连接成功");
                    return;
                }
                channelFuture.channel().eventLoop().schedule(()->{
                    System.out.println("重写连接中");
                    connect();
                }, 2000, TimeUnit.MILLISECONDS);
            }
        });
    }
}
